import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const router = useRouter()

  const login = async (username, password) => {
    try {
      const res = await request.post('/auth/login', { username, password })
      token.value = res.data.token
      localStorage.setItem('token', res.data.token)
      await router.push('/')
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const register = async (username, password) => {
    try {
      await request.post('/auth/register', { username, password })
      return await login(username, password)
    } catch (error) {
      return Promise.reject(error)
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    router.push('/login')
  }

  const getUserInfo = async () => {
    try {
      const res = await request.get('/users/current')
      userInfo.value = res.data
      return res
    } catch (error) {
      return Promise.reject(error)
    }
  }

  return {
    token,
    userInfo,
    login,
    register,
    logout,
    getUserInfo
  }
}) 